package com.ruoyi.hatha.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.hatha.domain.*;
import com.ruoyi.hatha.service.*;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.tools.HttpRequest;
import com.ruoyi.tools.TemplateData;
import com.ruoyi.tools.WxTool;
import org.junit.Test;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 预约管理Controller
 * 
 * @author Dong
 * @date 2024-01-02
 */
@RestController
@RequestMapping("/hatha/yuyue")
public class PYuyueController extends BaseController
{
    @Autowired
    private IPYuyueService pYuyueService;
    @Autowired
    private IPMykcService mykcService;
    @Autowired
    private IPKechengService kechengService;
    @Autowired
    private IPHexiaojiluService hexiaojiluService;
    @Autowired
    private IPYkechengService ykechengService;
    @Autowired
    private IPKcbService kcbService;
    @Autowired
    private IPTeachersService teacherService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IPMendianService mendianService;
    @Autowired
    private IPYueService yueService;
    @Autowired
    private IPMyvipService myvipService;
    @Autowired
    private IPKcOrderService orderService;

    /**
     * 查询预约管理列表
     */
    @PreAuthorize("@ss.hasPermi('hatha:yuyue:list')")
    @GetMapping("/list")
    public TableDataInfo list(PYuyue pYuyue)
    {
        startPage();
        List<PYuyue> list = pYuyueService.selectPYuyueList(pYuyue);
        return getDataTable(list);
    }

    @GetMapping("/listall")
    public AjaxResult listall()
    {
        List<PYuyue> list = pYuyueService.selectPYuyueList(null);
        return AjaxResult.success(list);
    }

    /**
     * 导出预约管理列表
     */
    @PreAuthorize("@ss.hasPermi('hatha:yuyue:export')")
    @Log(title = "预约管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PYuyue pYuyue)
    {
        List<PYuyue> list = pYuyueService.selectPYuyueList(pYuyue);
        ExcelUtil<PYuyue> util = new ExcelUtil<PYuyue>(PYuyue.class);
        util.exportExcel(response, list, "预约管理数据");
    }

    /**
     * 获取预约管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('hatha:yuyue:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(pYuyueService.selectPYuyueById(id));
    }

    @GetMapping(value = "/quxiaoyuyue")
    public AjaxResult quxiaoyuyue(Long id)
    {
        PYuyue p = pYuyueService.selectPYuyueById(id);


        p.setState(1);
        pYuyueService.updatePYuyue(p);

        if(p.getVid()!=null){
            Long vid = p.getVid();
            PMyvip pm = myvipService.selectPMyvipById(vid);
            if("4".equals(pm.getType())){
                pm.setSycs(pm.getSycs()+1);
                myvipService.updatePMyvip(pm);
            }
        }

        return success();
    }

    @GetMapping(value = "/getmyyy")
    public AjaxResult getmyyy()
    {
        Long uid = SecurityUtils.getUserId();

        PYuyue pyy = new PYuyue();
        pyy.setUid(uid);
        pyy.setState(0);
        List<PYuyue> lpyy = pYuyueService.selectPYuyueList(pyy);

        for (int i=0;i<lpyy.size();i++){
            Long kid = lpyy.get(i).getKcid();

            PKecheng pkc = kechengService.selectPKechengById(kid);

            lpyy.get(i).setKc(pkc);

        }

        return success(lpyy);
    }


    @GetMapping(value = "/getuseryy")
    public AjaxResult getuseryy(Long uid)
    {
        PYuyue pyy = new PYuyue();
        pyy.setUid(uid);
        pyy.setState(0);
        List<PYuyue> lpyy = pYuyueService.selectPYuyueList(pyy);

        for (int i=0;i<lpyy.size();i++){
            Long kid = lpyy.get(i).getKcid();

            PKecheng pkc = kechengService.selectPKechengById(kid);

            lpyy.get(i).setKc(pkc);

        }

        return success(lpyy);
    }


    @GetMapping(value = "/hexiao")
    public AjaxResult hexiao(Long yyid)
    {
        PYuyue pyy = pYuyueService.selectPYuyueById(yyid);
        pyy.setState(5);//已核销

        //查询是否需要扣余额
        Long kid = pyy.getKcid();
        PKecheng pkc = kechengService.selectPKechengById(kid);
        if(pkc.getKf()==1){//需要扣费
            Integer kfye = Integer.valueOf(pkc.getKcje());

            //查询用户余额
            PYue pYue = new PYue();
            pYue.setUid(pyy.getUid());
            PYue np = yueService.getCount(pYue);
            Integer ye = np.getNum();

            if(ye<kfye){
                return AjaxResult.error("可用余额不足",null);
            }else{
                PYue pYue1 = new PYue();
                pYue1.setUid(pyy.getUid());
                pYue1.setNum(0-kfye);
                pYue1.setCreateUser(SecurityUtils.getUserId());
                pYue1.setCreateTime(new Date());
                pYue1.setType(2);//充值
                yueService.insertPYue(pYue1);
            }
        }


        Long mkid = pyy.getMkid();

        if(mkid != null){
            PMykc pmk = mykcService.selectPMykcById(mkid);
            pmk.setIsused(1);//已核销

            Long oid = pmk.getOid();
            mykcService.updatePMykc(pmk);

            if(oid != null){
                PKcOrder order = orderService.selectPKcOrderById(oid);
                order.setState(2);
                orderService.updatePKcOrder(order);
            }

        }


        pYuyueService.updatePYuyue(pyy);


        //插入核销记录
        PHexiaojilu phx = new PHexiaojilu();
        phx.setBuyid(pyy.getUid());
        phx.setUid(SecurityUtils.getUserId());
        phx.setMsg("核销成功");
        phx.setKid(pyy.getKcid());
        phx.setStatus("0");
        phx.setCreateTime(new Date());
        hexiaojiluService.insertPHexiaojilu(phx);
        return success(yyid);
    }

    public void sendReq(){
       String obj = HttpRequest.sendGet("http://127.0.0.1:8998/hatha/yuyue/sendMsg","");
        System.out.println(obj);
    }

    @GetMapping("/sendMsg")
    public void sendMsg(){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy年MM月dd日");
        LocalDate today = LocalDate.now(); // 获取今天的日期
        LocalDate threeDaysLater = today.plusDays(3); // 在今天的基础上加3天
//        // 将LocalDate转换为ZonedDateTime
//        ZonedDateTime zonedDateTime = threeDaysLater.atStartOfDay(ZoneId.systemDefault());
//        // 将ZonedDateTime转换为Date
//        Date dateThreeDaysLater = Date.from(zonedDateTime.toInstant());
//        PYuyue pp = new PYuyue();
//        pp.setYytime(dateThreeDaysLater);
        List<PYuyue> ly = pYuyueService.selectPYuyueListByDate(threeDaysLater.toString());

        for(int i=0;i<ly.size();i++){
            Long uid = ly.get(i).getUid();
            Long ykid = ly.get(i).getYkid();
            PYkecheng ykecheng = ykechengService.selectPYkechengById(ykid);

            PKecheng kc = kechengService.selectPKechengById(ykecheng.getKid());

            PMendian md = mendianService.selectPMendianById(kc.getMid());

            PTeachers teachers = teacherService.selectPTeachersById(ykecheng.getTeacher());


            SysUser su = sysUserService.selectUserById(uid);
            List<String> openids = new ArrayList<>();
            openids.add(su.getOpenid());

            Map map = new HashMap<>();

            String ddd = dateFormat2.format(ly.get(i).getYytime()) + " "+ykecheng.getTimeStr();

            map.put("thing25", new TemplateData(kc.getName()));
            map.put("time2", new TemplateData(ddd));
            map.put("thing8", new TemplateData(md.getName()));
            map.put("thing18", new TemplateData(teachers.getName()));

            String tplId = "4shh02gTIwwAmyl7iE74LH6LJWZt5JPIZMKlgwDGLi0";

            WxTool.sendMsgMultithreading(openids, map, tplId, null);

        }


    }


    /**
     * 新增预约管理
     */
    @PreAuthorize("@ss.hasPermi('hatha:yuyue:add')")
    @Log(title = "预约管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PYuyue pYuyue)
    {
        return toAjax(pYuyueService.insertPYuyue(pYuyue));
    }

    @PostMapping("/addyuyue")
    public AjaxResult addyuyue(@RequestBody PYuyue pYuyue)
    {
        pYuyue.setUid(SecurityUtils.getUserId());
        pYuyue.setCreatetime(new Date());

        Long ykid = pYuyue.getYkid();

        PYkecheng ykecheng = ykechengService.selectPYkechengById(ykid);

        pYuyue.setRid(ykecheng.getRoomId());
        pYuyue.setLid(ykecheng.getTeacher());

        if("0".equals(pYuyue.getVid().toString())){//优先扣除会员卡次数
            pYuyue.setVid(null);
        }
        pYuyueService.insertPYuyue(pYuyue);

        if(!"0".equals(pYuyue.getVid().toString())){//扣除次数，只有次卡可扣除
            Long vid = pYuyue.getVid();
            PMyvip pm = myvipService.selectPMyvipById(vid);
            if("4".equals(pm.getType())){
                pm.setSycs(pm.getSycs()-1);
                myvipService.updatePMyvip(pm);
            }
        }

        //发送成功消息
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        List<String> openids = new ArrayList<>();
        openids.add(sysUser.getOpenid());


        Map map = new HashMap<>();

        PKecheng pkc = kechengService.selectPKechengById(pYuyue.getKcid());

        PYkecheng yk = ykechengService.selectPYkechengById(pYuyue.getYkid());

        PTeachers teachers = teacherService.selectPTeachersById(yk.getTeacher());

        map.put("thing1", new TemplateData(pkc.getName()));
        map.put("thing6", new TemplateData(teachers.getName()));
        map.put("time7", new TemplateData(yk.getTimeStr()));
        map.put("thing5", new TemplateData("请提前十分钟到场"));

        String tplId = "Z2IBbO9uhK6ZKihcCAqr45pWBxocbZ_zYHEN3JN83fI";

        WxTool.sendMsgMultithreading(openids, map, tplId, null);

        return AjaxResult.success("预约成功");
    }

    @GetMapping(value = "/getyuyuekecheng")
    public AjaxResult getInfo(Long mid,Long did,Long lid,Long fid) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        PYkecheng pYkecheng = new PYkecheng();
        pYkecheng.setBid(did);
        pYkecheng.setMid(mid);
        pYkecheng.setFid(fid);
        if(lid!=null && lid !=0){
            pYkecheng.setTeacher(lid);
        }

        //List<PYkecheng> pYkechengList = ykechengService.selectPYkechengList(pYkecheng);

        List<PYkecheng> pYkechengList = ykechengService.selectPYkechengListInfo(pYkecheng);

        PKcb kcb = kcbService.selectPKcbById(did);
        Long uid = SecurityUtils.getUserId();
        if(pYkechengList.size()==0){
            return  AjaxResult.success("空数据",new ArrayList<>());
        }
        //Long[] ids1 = new Long[pYkechengList.size()];
        for(int i=0;i<pYkechengList.size();i++){
            //ids1[i] = pYkechengList.get(i).getKid();

            PKecheng okc = kechengService.selectPKechengById(pYkechengList.get(i).getKid());

            //查询VIP绑定分类课程
            PMyvip m = new PMyvip();
            m.setUid(SecurityUtils.getUserId());
            m.setFid(fid);//分类
            PMyvip pmv = myvipService.getMyvip(m);

            okc.setMyvip(pmv);

            pYkechengList.get(i).setMyvip(pmv);


            PYuyue py = new PYuyue();
            py.setKcid(pYkechengList.get(i).getKid());
            py.setYytime(kcb.getDateStr());
            py.setState(0);
            py.setLid(pYkechengList.get(i).getTeacher());
            py.setRid(pYkechengList.get(i).getRoomId());
            List<PYuyue> lpyy = pYuyueService.selectPYuyueList(py);
            Integer yyy = lpyy.size();//总预约人数

            PYuyue py1 = new PYuyue();
            py1.setUid(uid);
            py1.setKcid(pYkechengList.get(i).getKid());
            py1.setYytime(kcb.getDateStr());
            py1.setState(0);
            py1.setLid(pYkechengList.get(i).getTeacher());
            py1.setRid(pYkechengList.get(i).getRoomId());
            List<PYuyue> lpyy2 = pYuyueService.selectPYuyueList(py1);
            Integer wyy = lpyy2.size();//我预约的

            if(wyy>0)
                okc.setYid(lpyy2.get(0).getId());

            Integer gm = 0;
            List<PMykc> lmkc = new ArrayList<>();


            PYuyue py3 = new PYuyue();
            py3.setUid(uid);
            py3.setKcid(pYkechengList.get(i).getKid());
            py3.setState(0);
            py3.setLid(pYkechengList.get(i).getTeacher());
            py3.setRid(pYkechengList.get(i).getRoomId());
            List<PYuyue> lpyy3 = pYuyueService.selectPYuyueList(py3);
            List<Long> ll = new ArrayList<>();
            for(int li=0;li<lpyy3.size();li++){
                ll.add(lpyy3.get(li).getMkid());
            }

            if(ll.size()==0&&lpyy3.size()==0){//无预约
                PMykc mkc = new PMykc();
                mkc.setIsused(0);
                mkc.setUid(uid);
                mkc.setKcid(pYkechengList.get(i).getKid());
                lmkc = mykcService.selectPMykcList(mkc);
                gm = lmkc.size();
            }else{
                String ids = "'"+ StringUtils.join(ll,"','")+"'";
                lmkc = mykcService.selectPMykcListByMkid(ids,uid,pYkechengList.get(i).getKid());
                gm = lmkc.size();
            }

            if(gm>0){
                okc.setMkid(lmkc.get(0).getId());
            }

            okc.setYyy(yyy);
            okc.setWyy(wyy);
            okc.setYgm(gm);

            pYkechengList.get(i).setpKecheng(okc);
        }



//        List<PKecheng> lpkc = kechengService.selectPKechengListByIds(ids1);
//
//        for(int i=0;i<lpkc.size();i++){
//            Long kcid = lpkc.get(i).getId();
//
//            PYuyue py = new PYuyue();
//            py.setKcid(kcid);
//            py.setYytime(kcb.getDateStr());
//            py.setState(0);
//            List<PYuyue> lpyy = pYuyueService.selectPYuyueList(py);
//            Integer yyy = lpyy.size();//总预约人数
//
//            PYuyue py1 = new PYuyue();
//            py1.setUid(uid);
//            py1.setKcid(kcid);
//            py1.setYytime(kcb.getDateStr());
//            py1.setState(0);
//            List<PYuyue> lpyy2 = pYuyueService.selectPYuyueList(py1);
//            Integer wyy = lpyy2.size();//我预约的
//
//            if(wyy>0)
//                lpkc.get(i).setYid(lpyy2.get(0).getId());
//
//            Integer gm = 0;
//            List<PMykc> lmkc = new ArrayList<>();
//
//
//            PYuyue py3 = new PYuyue();
//            py3.setUid(uid);
//            py3.setKcid(kcid);
//            py3.setState(0);
//            List<PYuyue> lpyy3 = pYuyueService.selectPYuyueList(py3);
//            List<Long> ll = new ArrayList<>();
//            for(int li=0;li<lpyy3.size();li++){
//                ll.add(lpyy3.get(li).getMkid());
//            }
//
//            if(ll.size()==0&&lpyy3.size()==0){//无预约
//                PMykc mkc = new PMykc();
//                mkc.setIsused(0);
//                mkc.setUid(uid);
//                mkc.setKcid(kcid);
//                lmkc = mykcService.selectPMykcList(mkc);
//                gm = lmkc.size();
//            }else{
//                String ids = "'"+ StringUtils.join(ll,"','")+"'";
//                lmkc = mykcService.selectPMykcListByMkid(ids,uid,kcid);
//                gm = lmkc.size();
//            }
//
//            if(gm>0){
//                lpkc.get(i).setMkid(lmkc.get(0).getId());
//            }
//
//            lpkc.get(i).setYyy(yyy);
//            lpkc.get(i).setWyy(wyy);
//            lpkc.get(i).setYgm(gm);
//
//        }



        return success(pYkechengList);
    }



//    @GetMapping(value = "/getyuyuekecheng")
//    public AjaxResult getInfo(Long mid,String date) throws ParseException {
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//        PKecheng p = new PKecheng();
//        p.setMid(mid);
//        List<PKecheng> lpkc = kechengService.selectPKechengList(p);
//        Long uid = SecurityUtils.getUserId();
//        for(int i=0;i<lpkc.size();i++){
//            Long kcid = lpkc.get(i).getId();
//
//            PYuyue py = new PYuyue();
//            py.setKcid(kcid);
//            py.setYytime(dateFormat.parse(date));
//            py.setState(0);
//            List<PYuyue> lpyy = pYuyueService.selectPYuyueList(py);
//            Integer yyy = lpyy.size();//总预约人数
//
//            PYuyue py1 = new PYuyue();
//            py1.setUid(uid);
//            py1.setKcid(kcid);
//            py1.setYytime(dateFormat.parse(date));
//            py1.setState(0);
//            List<PYuyue> lpyy2 = pYuyueService.selectPYuyueList(py1);
//            Integer wyy = lpyy2.size();//我预约的
//
//            if(wyy>0)
//                lpkc.get(i).setYid(lpyy2.get(0).getId());
//
//            Integer gm = 0;
//            List<PMykc> lmkc = new ArrayList<>();
//
//
//            PYuyue py3 = new PYuyue();
//            py3.setUid(uid);
//            py3.setKcid(kcid);
//            py3.setState(0);
//            List<PYuyue> lpyy3 = pYuyueService.selectPYuyueList(py3);
//            List<Long> ll = new ArrayList<>();
//            for(int li=0;li<lpyy3.size();li++){
//                ll.add(lpyy3.get(li).getMkid());
//            }
//
//            if(ll.size()==0&&lpyy3.size()==0){//无预约
//                PMykc mkc = new PMykc();
//                mkc.setIsused(0);
//                mkc.setUid(uid);
//                mkc.setKcid(kcid);
//                lmkc = mykcService.selectPMykcList(mkc);
//                gm = lmkc.size();
//            }else{
//                String ids = "'"+ StringUtils.join(ll,"','")+"'";
//                lmkc = mykcService.selectPMykcListByMkid(ids,uid,kcid);
//                gm = lmkc.size();
//            }
//
//            if(gm>0){
//                lpkc.get(i).setMkid(lmkc.get(0).getId());
//            }
//
//            lpkc.get(i).setYyy(yyy);
//            lpkc.get(i).setWyy(wyy);
//            lpkc.get(i).setYgm(gm);
//
//        }
//
//
//
//        return success(lpkc);
//    }



    /**
     * 修改预约管理
     */
    @PreAuthorize("@ss.hasPermi('hatha:yuyue:edit')")
    @Log(title = "预约管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PYuyue pYuyue)
    {
        return toAjax(pYuyueService.updatePYuyue(pYuyue));
    }

    /**
     * 删除预约管理
     */
    @PreAuthorize("@ss.hasPermi('hatha:yuyue:remove')")
    @Log(title = "预约管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(pYuyueService.deletePYuyueByIds(ids));
    }
}
